//
//  HMShareManager.swift
//  SinaWeiBo
//
//  Created by immncjykeny on 2017/5/2.
//  Copyright © 2017年 immncjykeny. All rights reserved.
//

import UIKit
import AFNetworking
enum HTTPMethod {
    case GET
    case POST
}

class HMShareManager: AFHTTPSessionManager {
    //闭包
    static let shared:HMShareManager = { () -> HMShareManager in
        let instance = HMShareManager()
        
        //设置反序列化支持数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
        
    }()
    
     lazy var userAccount = HMUserAccount()
    //用户登录标记 计算型属性
    var userlogon:Bool{
        return userAccount.access_token != nil
    }
    
    //MARK:专门负责拼接token的请求方法
    func tokenRequest(requestType:HTTPMethod = .GET,urlString : String, parameters : [String : Any]?, resultBlock : @escaping(_ responseObj:[String:Any]?, _ isSuccess:Bool) -> ()){
        
        //处理token字典  token是否为nil 如果是 直接返回
        guard let token = userAccount.access_token else {
            //FIXME:发送通知 提示用户登录
            print("没有 token ! 需要登录")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: HMUserShouldLoginNotification), object: nil)
            
            resultBlock(nil, false)
            
            
            return
        }
        //处理parameters 如果没有 创建一个参数字典
        var parameters = parameters
        
        if parameters == nil {
            
            parameters = [String:Any]()
        }
        //在此处设置参数字典 而且一定有值
        parameters!["access_token"] = token
        
    request(urlString: urlString, parameters: parameters, resultBlock: resultBlock)
        
    }
    //使用一个函数封装AFN的GET和POST请求
    func request(requestType :HTTPMethod = .GET, urlString : String, parameters : [String : Any]?, resultBlock : @escaping(_ responseObj:[String:Any]?, _ isSuccess:Bool) -> ()) {
        
        // 成功闭包
        let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in
            resultBlock(responseObj as? [String : Any], true)
        }
        
        // 失败的闭包
        let failureBlock = { (task: URLSessionDataTask?, error: Error) in
            resultBlock(nil, false)
           if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token过期了")
            //FIXME:发送通知 提示用户再次登录，谁接到通知 谁去处理
            
             NotificationCenter.default.post(name: NSNotification.Name(rawValue: HMUserShouldLoginNotification), object: "bad token")
            }
        }
        
        // Get 请求
        if requestType == .GET {
            get(urlString, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)
        }
        
        // Post 请求
        if requestType == .POST {
            post(urlString, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)
        }
    }
        
        
        
        
    

}
